import {
  SAVE_TOKEN,
  FETCH_USER_SUCCESS,
  FETCH_USER_FAILURE,
  LOGOUT,
  UPDATE_USER,
  TOGGLE_SIDEBAR
} from './mutation-types.js';
import Cookies from 'js-cookie';

export default {

  [SAVE_TOKEN] (state, { token, remember }) {
    Cookies.set('token', token, { expires: remember ? 365 : null });
    state.token = token;
  },
  [FETCH_USER_FAILURE] (state) {
    state.token = null;
    Cookies.remove('token');
  },
  [FETCH_USER_SUCCESS] (state, user) {
    if(user['avatar'] || user['avatar'].length === 1){
      user['avatar']=user['avatar'][0];
    }
    state.user = user;
  },

  [LOGOUT] (state) {
    state.user = null;
    state.token = null;
    Cookies.remove('token');
  },
  [UPDATE_USER] (state, { user }) {
    state.user = user;
  },

  [TOGGLE_SIDEBAR]: state => {
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1);
    } else {
      Cookies.set('sidebarStatus', 0);
    }
    state.sidebar.opened = !state.sidebar.opened;
  }
};
